import axios from '../../../../utils/axios'
const app = getApp();
Page({
  data: {
    courseDetail: [],
    childrenDetail: [],
    curChildren: []
  },
  onLoad: async function (options) {
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('sendData', (res) => {
      this.setData({
        courseDetail: res.data,
      })
    });
    // 查询我的小孩数据测试
    let res = await axios({
      url: '/api/school/student/self',
      data: {
        id: app.globalData.userInfo.id,
        openid: app.globalData.userInfo.openid,
        type: ''
      },
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    });
    let childrenDetail;
    if (res.data.length > 0)
      childrenDetail = res.data;
    else
      childrenDetail = [{ id: '', name: '暂无小孩' }]
    this.setData({
      childrenDetail,
      curChildren: childrenDetail[0]
    })
    console.log('小孩数据', this.data.childrenDetail);
  },
  onReady: function () {

  },
  onShow: function () {

  },
  onHide: function () {

  },
  onUnload: function () {

  },

  onPullDownRefresh: function () {

  },

  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  },
  getRemark(e) {
    let temp = { ...this.data.courseDetail, remark: e.detail.value };
    this.setData({
      courseDetail: temp
    })
  },
  async goToPay() {
    let toPay = async () => {
      // 获取支付参数
      let userInfo = app.globalData.userInfo;
      let payOption = await axios({
        url: '/api/wx/pay/createOrder',
        method: 'post',
        data: {
          openid: userInfo.openId,
          body: `${this.data.courseDetail.name}订单`,
          appid: 'wxe4f65fd9f5a232f9',
          price: this.data.courseDetail.price,
          // price: 0.01,
          tradeType: 'JSAPI',
          remark: this.data.courseDetail.remark,
          detail: JSON.stringify({
            goodDetails: [{
              uid: userInfo.id,
              phoneNumber: userInfo.phoneNumber,
              studentId: this.data.curChildren.id,
              courseId: this.data.courseDetail.id,
              price: this.data.courseDetail.price,
            }],
          }),
        },
        header: {
          'Authorization': wx.getStorageSync('token')
        }
      });
      if (payOption.statusCode == '703') {
        wx.showToast({
          title: '您未绑定您的宝宝!请进行备注说明或者联系学校哦!',
          icon: 'none',
          duration: 1500,
          mask: false,
        });
        return;
      }
      let [timeStamp, nonceStr, packageValue, signType, paySign] = [
        payOption.data.timeStamp,
        payOption.data.nonceStr,
        payOption.data.packageValue,
        payOption.data.signType,
        payOption.data.paySign
      ]
      // 支付
      wx.requestPayment({
        timeStamp,
        nonceStr,
        package: packageValue,
        signType,
        paySign,
        // 成功
        success: paidRes => {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500,
            mask: false,
          });
          wx.reLaunch({
            url: `/components/page/payResult/payResult?msg=${paidRes.errMsg}&isPaid=${true}`,
          });
        },
        // 失败
        fail: err => {
          wx.showToast({
            title: '支付失败',
            icon: 'none',
            duration: 1500,
            mask: false,
          });
          wx.reLaunch({
            url: `/components/page/payResult/payResult?msg=${err.errMsg}&isPaid=${false}`,
          })
        },
        complete: (res) => {
          console.log('通用支付回调', res);
        }
      });
    }
    // 判断小孩子地区是否符合课程地区
    let res = await axios({
      url: '/api/wx/pay/checkChildFrom',
      method: 'post',
      data: {
        officeId: this.data.courseDetail.officeId,
        studentId: this.data.curChildren.id
      },
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    });
    if (!res.data) {
      wx.showModal({
        title: '提示',
        content: '您的宝宝地区与课程地区不符',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: async (result) => {
          if (result.confirm) {
            toPay()
          }
        },
        fail: () => {
          return
        }
      });
    }
    else {
      toPay();
    }
  },
  changeCurChildren(e) {
    this.setData({
      curChildren: e.detail.value
    })
  }
});